package com.wink_172.library.utils

import android.graphics.Bitmap
import android.graphics.Canvas
import android.view.View
import androidx.core.widget.NestedScrollView
import org.xutils.x

/**
 *view截屏管理工具
 */
object ViewScreenUtils {
    private const val TAG = "ViewScreenUtils"
    fun createMPTViewBitmap2(view: View, height: Int): Bitmap? {

        val bitmap =
            Bitmap.createBitmap(
                DisplayUtil.getScreenWidth(x.app()),
                height,
                Bitmap.Config.ARGB_8888
            )

        val canvas = Canvas(bitmap)
        view.draw(canvas)
        return bitmap
    }
    /**
     * 全屏
     * */
    fun createMPTViewBitmapDanceSingle(view: View): Bitmap? {
        val bitmap =
            Bitmap.createBitmap(
                DisplayUtil.getScreenWidth(x.app()),
                DisplayUtil.getScreenHeight(x.app()),
                Bitmap.Config.ARGB_8888
            )

        val canvas = Canvas(bitmap)
        view.draw(canvas)
        return bitmap
    }

    fun createMPTViewBitmap(view: View): Bitmap? {
//        val screenWidth = DisplayUtil.getScreenWidth(x.app()) - DisplayUtil.dp2px(x.app(), 20 * 2)
//        val hight = screenWidth - DisplayUtil.dp2px(this, 20) * 2

        if (view.measuredWidth <= 0 || view.measuredHeight <= 0) {
            return null
        }

        val bitmap =
            Bitmap.createBitmap(
                view.measuredWidth,
                view.measuredHeight,
                Bitmap.Config.ARGB_8888
            )
        val canvas = Canvas(bitmap)
        view.draw(canvas)
        return bitmap
    }

    /**
     * createMPTViewBitmap中scrollview最大只能包含屏幕高度
     * 这个可以包含scrollview的全部屏幕
     * 但是一般推荐用scrollview中的Linearlayout控件，直接.height获取到的是真实高度
     *
     * @param scrollView
     * @return
     */
    fun getBitmapByContainer(scrollView: NestedScrollView): Bitmap? {
        var h = 0
        var bitmap: Bitmap? = null
        // 获取scrollview实际高度
        for (i in 0 until scrollView.childCount) {
            h += scrollView.getChildAt(i).height //获取scrollView的屏幕高度
            scrollView.getChildAt(i).setBackgroundColor(
                x.app().resources.getColor(com.wink_172.library.R.color.white)
            )
        }
        //如果传的参数不是NestedScrollView，则不需要循环遍历高度
//        h += scrollView.getHeight();//获取scrollView的屏幕高度
//        scrollView.setBackgroundColor(
//                    Color.parseColor("#ffffff"));
        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(
            scrollView.width, h,
            Bitmap.Config.RGB_565
        )
        val canvas = Canvas(bitmap) //把创建的bitmap放到画布中去
        scrollView.draw(canvas) //绘制canvas 画布
        return bitmap
    }
}